<script lang="ts" setup>
import { formatTimeAgo } from '@vueuse/core';
import { toTypedSchema } from '@vee-validate/zod';
import { z } from 'zod';
import { useForm } from 'vee-validate';
import { type Comment, commentApi, type CommentChild, type CommentChildList } from '~/utils/api/comment-api';
import { toast } from '~/components/ui/toast';
import { useUserStore } from '~/composables/store/user-store';

const { articleId, comment } = defineProps<{
	articleId: number;
	comment: Comment;
}>();

const userStore = useUserStore();

// 格式化时间
const getFormatTimeAgo = (date: string | Date) => {
	return formatTimeAgo(
		typeof date === 'string' ? new Date(date) : date,
		{
			max: 86400000, // 一天
			fullDateFormatter(date) {
				return date.toLocaleString().replaceAll('/', '-');
			},
			messages: {
				justNow: '刚刚',
				past: (n: string | number) => `${n}`.match(/\d/) ? `${n}前` : `${n}`,
				future: (n: string | number) => `${n}`.match(/\d/) ? `${n}后` : `${n}`,
				// year: (n: number, _: boolean) => `${n}年`,
				// month: (n: number, _: boolean) => `${n}月`,
				// week: (n: number, _: boolean) => `${n}周`,
				day: (n: number, _: boolean) => `${n}天`,
				hour: (n: number) => `${n}小时`,
				minute: (n: number) => `${n}分钟`,
				second: (n: number) => `${n}秒`,
				invalid: '',
			},
		},
	);
};
// ------------------------
// -------- 子评论列表 --------
const childrenList = ref<CommentChildList>();
const children = ref(comment.children);
// 是否查看更多子评论
const isSeeMoreChildren = ref(false);
// 查看更多子评论
const seeMoreChildrenComment = () => {
	isSeeMoreChildren.value = true;
	commentApi.queryChildrenListClient(comment.commentId).then((res) => {
		childrenList.value = res.data;
		children.value = res.data.list;
	});
};
// 分页查询子评论
const onPageChanged = (value: number) => {
	commentApi.queryChildrenListClient(comment.commentId, value).then((res) => {
		children.value = res.data.list;
	});
};

// ------------------------
// -------- 回复功能 --------
// 是否显示回复输入框
const isShowReplyInput = ref(false);
// 回复的评论
const replyComment = ref<Comment | CommentChild>();
// 点击回复按钮
const handleReplyClick = (comment: Comment | CommentChild) => {
	isShowReplyInput.value = !(comment.commentId === replyComment.value?.commentId && isShowReplyInput.value);
	replyComment.value = comment;
};
// ---- 回复输入框表单 ----
const formSchema = toTypedSchema(z.object({
	reply: z.string({ required_error: '回复不能为空', message: '请输入回复' }),
}));

const { handleSubmit, handleReset } = useForm({
	validationSchema: formSchema,
});

const onSubmit = handleSubmit(({ reply }) => {
	// 判断是否登录
	if (!userStore.isLogin) {
		toast({
			description: '请先登录',
		});
		return;
	}

	// 发送回复
	commentApi.sendComment(articleId, reply, replyComment.value?.commentId).then(async (res) => {
		if (res.code === 200) {
			toast({
				description: '评论成功',
			});
			handleReset();
			isShowReplyInput.value = false;
			seeMoreChildrenComment();
		}
		else {
			toast({
				description: res.message.toString(),
			});
		}
	}).catch((err) => {
		toast({
			description: err.data.message,
		});
	});
});
</script>

<template>
	<div class="flex overflow-x-auto">
		<!--    头像    -->
		<div class="mr-2">
			<Avatar>
				<AvatarImage
					alt="avatar"
					src="https://github.com/radix-vue.png"
				/>
				<AvatarFallback>CN</AvatarFallback>
			</Avatar>
		</div>
		<!--    名字、内容    -->
		<div class="w-full">
			<p class="mb-2 text-sm">
				{{ comment.user.nickName }}
			</p>
			<span class="break-all">
				{{ comment.content }}
			</span>
			<!--  日期、回复按钮  -->
			<div class="flex gap-4 text-sm text-neutral-500">
				<div>
					{{ getFormatTimeAgo(comment.updateDate || '') }}
				</div>
				<div
					class="cursor-pointer"
					@click="handleReplyClick(comment)"
				>
					回复
				</div>
			</div>
			<!--   子评论   -->
			<div
				v-for="child in children"
				:key="child.commentId"
				class=""
			>
				<div class="flex mt-3">
					<Avatar
						class="mr-1"
						size="xs"
					>
						<AvatarImage
							alt="avatar"
							src="https://github.com/radix-vue.png"
						/>
						<AvatarFallback>CN</AvatarFallback>
					</Avatar>
					<div>
						<div class="break-keep">
							<span class="text-sm text-neutral-500 mr-2">{{ child.user.nickName }}</span>
							<span>{{ child.user.id === comment.user.id ? '' : `@${child.replyUser.nickName}` }}</span>
							<span class="break-all">{{ child.content }}</span>
						</div>
						<div class="flex gap-4 text-sm text-neutral-500">
							<div>
								{{ getFormatTimeAgo(child.updateDate || '') }}
							</div>
							<div
								class="cursor-pointer"
								@click="handleReplyClick(child)"
							>
								回复
							</div>
						</div>
					</div>
				</div>
			</div>
			<!--   查看更多、分页   -->
			<div
				v-if="comment.childrenCount>0 && !isSeeMoreChildren"
				class="flex mt-2 text-sm text-neutral-500"
			>
				共{{ comment.childrenCount }}条评论
				<span
					v-if="comment.childrenCount>2"
					class="ml-2 cursor-pointer"
					@click="seeMoreChildrenComment"
				>
					查看更多
				</span>
			</div>
			<!--   分页   -->
			<div v-if="isSeeMoreChildren && childrenList?.total||0 > 10">
				<Pagination
					v-slot="{ page }"
					:default-page="1"
					:sibling-count="1"
					:total="comment.childrenCount"
					show-edges
					@update:page="onPageChanged"
				>
					<PaginationList
						v-slot="{ items }"
						class="flex items-center gap-1 mt-1"
					>
						<PaginationPrev class="border-0 w-8 h-8" />

						<template v-for="(item, index) in items">
							<PaginationListItem
								v-if="item.type === 'page'"
								:key="index"
								:value="item.value"
								as-child
							>
								<Button
									:class="[item.value === page ? 'text-neutral-950' : 'text-neutral-400', 'border-0 w-8 h-8 p-0']"
									variant="ghost"
								>
									{{ item.value }}
								</Button>
							</PaginationListItem>
							<PaginationEllipsis
								v-else
								:key="item.type"
								:index="index"
							/>
						</template>

						<PaginationNext class="border-0 w-8 h-8" />
					</PaginationList>
				</Pagination>
			</div>
			<!--   回复输入框   -->
			<form
				v-show="isShowReplyInput"
				class="flex gap-2 mt-2"
				@submit="onSubmit"
			>
				<FormField
					v-slot="{ componentField }"
					name="reply"
				>
					<FormItem
						class="w-full"
					>
						<FormControl>
							<Input
								:placeholder="`回复${replyComment?.user.nickName}:`"
								type="text"
								v-bind="componentField"
							/>
						</FormControl>
						<FormMessage />
					</FormItem>
				</FormField>
				<Button type="submit">
					发送
				</Button>
			</form>
			<!--  分隔线  -->
			<div class="border-b h-1 w-full mt-4" />
		</div>
	</div>
</template>

<style scoped>

</style>
